<template>
  <n-modal v-bind="bindValue" v-model:show="showModal" :loading="loading" :closable="!loading" :title="propsRef?.title"
           class="w-[480px]" @close="closeModal" :negative-button-props="{size:'large', disabled: loading}"
           :positive-button-props="{size:'large', type:'primary'}" @negative-click="closeModal"
           @positive-click="confirmSubmit">
    <template #default>
      <slot name="default"></slot>
    </template>
  </n-modal>
</template>

<script setup>
import {computed, ref, unref, useAttrs} from 'vue'
import {defaultProps} from './modalProps'

const emit = defineEmits(['on-submit', 'on-close'])
const attr = useAttrs()
const props = defineProps({...defaultProps})
const showModal = ref(false)
const loading = ref(false)
const propsRef = ref(null)
const bindValue = computed(() => ({...attr, ...unref(props), ...unref(propsRef)}))

const setProps = modalProps => {
  propsRef.value = modalProps
}

const openModal = () => {
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
  loading.value = false
  emit('on-close')
}

const confirmSubmit = () => {
  loading.value = true
  return new Promise((resolve, reject) => {
    emit('on-submit')
  }).finally(() => {
    loading.value = false
  })
}

const modalMethods = {
  setProps,
  openModal
}

defineExpose({
  modalMethods
})
</script>

<style scoped>

</style>
